package com.sinodata.bsm.center.web.action.portlet;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.service.config.PortalService;
import com.sinodata.bsm.center.user.UserUtil;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.vo.PageConf;
import com.sinodata.bsm.common.vo.PageModuleDef;
import com.sinodata.bsm.common.vo.PagePortal;

public class PortalAction extends BaseAction<PagePortal> {
    private PagePortal entity;
    private String portalPage;
    @Autowired
    private PortalService portalService;

    /**
     * 删除组件
     */
    @Override
    public String delete() throws Exception {
        String pageId = request.getParameter("pageId");
        String userId = UserUtil.getInstance().getCurrentUser().getId();
        PagePortal portalPage = portalService.findPortalPageByUser(userId, pageId);
        String confId = request.getParameter("confId");
        PageConf pageConf = portalService.findPageConfById(Long.parseLong(confId));
        if (portalPage == null && !userId.equals("admin")) {
            Object[] objs;
            try {
                objs = clonePagePortal(userId, pageId);
                portalPage = (PagePortal) objs[0];
                List<PageConf> confList = (List<PageConf>) objs[1];
                for (int i = 0; i < confList.size(); i++) {
                    PageConf c = confList.get(i);
                    if (c.getPosx().intValue() == pageConf.getPosx() && c.getPosy().intValue() == pageConf.getPosy()) {
                        pageConf = c;
                        break;
                    }
                }
            } catch (Exception e) {

            }
        }

        portalService.deletePageConf(pageConf);

        return null;
    }

    @Override
    public String input() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String list() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    public String pageModuleTree() {
        List<PageModuleDef> list = portalService.findAll();
        JSONArray rootArray = new JSONArray();
        int index = 1;
        String typename = "";
        Map<String, JSONArray> map = new LinkedHashMap<String, JSONArray>();
        List<JSONObject> typeList = new ArrayList<JSONObject>();

        for (PageModuleDef page : list) {
            JSONArray arr = null;
            JSONObject json = new JSONObject();
            json.element("id", page.getJspPage());
            json.element("name", page.getTitle());
            if (!typename.equals(page.getTypename())) {
                arr = new JSONArray();
                map.put(page.getTypename(), arr);
            } else {
                arr = map.get(page.getTypename());
            }
            arr.add(json);
            typename = page.getTypename();
        }

        for (String str : map.keySet()) {
            JSONObject typejson = new JSONObject();
            typejson.element("id", "" + index);
            typejson.element("name", str);
            typejson.element("open", true);
            typejson.element("children", map.get(str));
            rootArray.add(typejson);
            index++;
        }
        Struts2Utils.renderText(rootArray.toString());

        return null;
    }

    @Override
    protected void prepareModel() throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public String save() throws Exception {
        String pageId = request.getParameter("pageId");
        String userId = UserUtil.getInstance().getCurrentUser().getId();
        PagePortal portalPage = portalService.findUserPortalById(Long.parseLong(pageId));
        int oldLen = portalPage.getColLength();
        PagePortal savedPagePortal = null;
        if (!portalPage.getUserAccount().equals(userId)) {
            Object[] objs = clonePagePortal(userId, portalPage.getPortalPage());
            savedPagePortal = (PagePortal) objs[0];

        } else {
            savedPagePortal = portalPage;
        }
        String colLength = request.getParameter("colLength");
        int len = Integer.parseInt(colLength);
        savedPagePortal.setColLength(len);
        savedPagePortal.setCol1(null);
        savedPagePortal.setCol2(null);
        savedPagePortal.setCol3(null);
        String col1 = request.getParameter("col1");
        String col2 = request.getParameter("col2");
        String col3 = request.getParameter("col3");
        if (len == 1) {
            savedPagePortal.setCol1(100);
        } else {
            savedPagePortal.setCol1(Integer.parseInt(col1));
            savedPagePortal.setCol2(Integer.parseInt(col2));
            if (len == 3) {
                savedPagePortal.setCol3(Integer.parseInt(col3));
            }
        }
        portalService.saveOrUpdatePagePortal(savedPagePortal);
        List<PageConf> confList = portalService.findPageConfByPagePortal(savedPagePortal.getId());
        if (confList != null && oldLen != len) {
            int startx = 0;
            int starty = 0;
            for (int i = 0; i < confList.size(); i++) {
                if (starty == len) {
                    starty = 0;
                    startx++;
                }
                PageConf conf = confList.get(i);
                conf.setPosy(starty);
                conf.setPosx(startx);
                starty++;
                portalService.saveOrUpdatePageConf(conf);
            }

        }

        return null;
    }

    /**
     * 参数页面设置
     * 
     * @return
     * @throws Exception
     */
    public String saveConf() throws Exception {
        String confId = request.getParameter("confId");
        PageConf pageConf = portalService.findPageConfById(Long.parseLong(confId));
        // /////////////////////////////////////////////////////////////
        PagePortal tmp = portalService.findUserPortalById(pageConf.getPagePortalId());
        String pageId = tmp.getPortalPage();
        String userId = UserUtil.getInstance().getCurrentUser().getId();
        PagePortal portalPage = portalService.findPortalPageByUser(userId, pageId);

        if (portalPage == null && !userId.equals("admin")) {
            Object[] objs;
            try {
                objs = clonePagePortal(userId, pageId);
                portalPage = (PagePortal) objs[0];
                List<PageConf> confList = (List<PageConf>) objs[1];
                for (int i = 0; i < confList.size(); i++) {
                    PageConf c = confList.get(i);
                    if (c.getPosx().intValue() == pageConf.getPosx() && c.getPosy().intValue() == pageConf.getPosy()) {
                        pageConf = c;
                        break;
                    }
                }
            } catch (Exception e) {

            }
        }
        // /////////////////////////////////////////////////////////////////
        String title = request.getParameter("cmpTitle");
        pageConf.setTitle(title);
        Enumeration en = request.getParameterNames();
        JSONObject argJson = new JSONObject();
        while (en.hasMoreElements()) {
            String args = (String) en.nextElement();
            if (args.indexOf("PARAM_") != -1) {
                String val = request.getParameter(args);
                argJson.element(args, val);
            }
        }

        pageConf.setParams(argJson.toString());
        portalService.saveOrUpdatePageConf(pageConf);
        return null;
    }

    /**
     * 页面显示顺序
     * 
     * @return
     */
    public String saveSeq() {
        try {
            String args = request.getParameter("args");
            String pageId = request.getParameter("pageId");
            String userId = UserUtil.getInstance().getCurrentUser().getId();
            PagePortal portalPage = portalService.findPortalPageByUser(userId, pageId);
            boolean needCopy = false;
            if (portalPage == null && !userId.equals("admin")) {
                PagePortal page = portalService.findPortalPageByUser("admin", pageId);
                try {

                    portalPage = page.clone();
                    portalPage.setUserAccount(userId);
                    portalService.saveOrUpdatePagePortal(portalPage);
                    needCopy = true;
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                }
            }

            String[] orders = args.split(",");
            for (int i = 0; i < orders.length; i++) {
                String[] values = orders[i].split("#");
                if (values[0].equals("")) {
                    continue;
                }
                Long confId = Long.parseLong(values[0]);

                Integer posx = Integer.parseInt(values[1]);
                Integer posy = Integer.parseInt(values[2]);
                PageConf conf = portalService.findPageConfById(confId);
                PageConf savedPageConf = null;
                if (needCopy) {
                    try {
                        savedPageConf = conf.clone();
                        savedPageConf.setPagePortalId(portalPage.getId());
                    } catch (CloneNotSupportedException e) {

                    }
                } else {
                    savedPageConf = conf;
                }
                savedPageConf.setPosx(posx);
                savedPageConf.setPosy(posy);
                portalService.saveOrUpdatePageConf(savedPageConf);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    private Object[] clonePagePortal(String userId, String portalPage) throws Exception {
        Object[] objs = new Object[2];
        PagePortal page = portalService.findPortalPageByUser("admin", portalPage);
        PagePortal clonePagePortal = page.clone();
        clonePagePortal.setUserAccount(userId);
        portalService.saveOrUpdatePagePortal(clonePagePortal);
        objs[0] = clonePagePortal;

        List<PageConf> exists = portalService.findPageConfByPagePortal(page.getId());
        List<PageConf> cloneList = new ArrayList<PageConf>();
        if (exists != null) {
            for (PageConf conf : exists) {
                PageConf clonePageConf = conf.clone();
                clonePageConf.setPagePortalId(clonePagePortal.getId());
                portalService.saveOrUpdatePageConf(clonePageConf);
                cloneList.add(clonePageConf);
            }
        }
        objs[1] = cloneList;

        return objs;
    }

    /**
     * 添加组件
     * 
     * @return
     */
    public String savePageConf() {
        String ids = request.getParameter("moduleIds");
        String pageId = request.getParameter("pageId");
        String userId = UserUtil.getInstance().getCurrentUser().getId();
        PagePortal portalPage = portalService.findPortalPageByUser(userId, pageId);
        List<PageConf> exists = null;
        if (portalPage == null && !userId.equals("admin")) {
            Object[] objs;
            try {
                objs = clonePagePortal(userId, pageId);
                portalPage = (PagePortal) objs[0];
                exists = (List<PageConf>) objs[1];
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else {
            exists = portalService.findPageConfByPagePortal(portalPage.getId());
            if (exists == null) {
                exists = new ArrayList<PageConf>();
            }
        }
        String[] arr = ids.split("#");

        int startPosx = 0;
        int startPosy = 0;
        if (exists != null && exists.size() > 0) {
            startPosx = exists.get(exists.size() - 1).getPosx();
            startPosy = exists.get(exists.size() - 1).getPosy();
            startPosy++;
        }

        for (int i = 0; i < arr.length; i++) {
            if (startPosy == portalPage.getColLength()) {
                startPosx++;
                startPosy = 0;
            }
            PageModuleDef def = portalService.findPageModuleDefId(arr[i]);
            PageConf conf = new PageConf();
            conf.setPagePortalId(portalPage.getId());
            conf.setPageModule(def.getJspPage());

            conf.setTitle(def.getTitle());
            conf.setPosx(startPosx);
            conf.setPosy(startPosy);
            conf.setParamPage(def.getPageDetail());
            portalService.saveOrUpdatePageConf(conf);
            startPosy++;
        }
        return null;
    }

    @Override
    public PagePortal getModel() {
        return entity;
    }

}
